package com.candicom.race.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;

class OuterCanvas extends JComponent {

    private final int gap = 5;
    private BufferedImage image;

    public OuterCanvas(Dimension _dim, Image _image) {

        image = new BufferedImage(_dim.width, _dim.height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gImage = (Graphics2D) image.getGraphics();
        gImage.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        gImage.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        gImage.setBackground(new Color(255, 255, 255, 0));
        gImage.clearRect(0, 0, _dim.width, _dim.height);
        gImage.drawImage(_image, null, null);
        gImage.dispose();

        Dimension dim = new Dimension(_dim.width + gap, _dim.height + gap);
        setPreferredSize(dim);
        setMinimumSize(dim);
        setMaximumSize(dim);
        setSize(dim);
    }

    void setInnerCanvas(InnerCanvas innerCanvas) {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(gap, gap, gap).addComponent(innerCanvas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGap(gap, gap, gap)));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(gap, gap, gap).addComponent(innerCanvas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGap(gap, gap, gap)));
    }

    @Override
    public void update(Graphics graphics) {
        Graphics2D g = (Graphics2D) graphics.create();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawImage(image, gap, gap, null);
        g.dispose();
    }

    @Override
    protected void paintComponent(Graphics graphics) {
        update(graphics);
    }
}
